﻿using System;
using System.Collections.Generic;
using System.Text;
using He.BLL;
using He.Common;
using System.Data;
using System.Text.RegularExpressions;
using System.Web;

namespace He.Web.UI
{
    public partial class HtmlHelper
    {

        #region 格式化输出日期
        public string FormateDate(object _date)
        {
            DateTime date = new DateTime();
            if (DateTime.TryParse(_date.ToString(), out date))
            {
                return string.Format("{0:yyyy-MM-dd}", date);
            }
            return _date.ToString();
        }
        public string FormateDateYM(object _date)
        {
            DateTime date = new DateTime();
            if (DateTime.TryParse(_date.ToString(), out date))
            {
                return string.Format("{0:yyyy-MM}", date);
            }
            return _date.ToString();
        }
        public string FormateDateD(object _date)
        {
            DateTime date = new DateTime();
            if (DateTime.TryParse(_date.ToString(), out date))
            {
                return string.Format("{0:dd}", date);
            }
            return _date.ToString();
        }
        #endregion

        #region 分类列表
        public string cates(string name)
        {
            BLL.channel bll = new BLL.channel();
            BLL.article abll = new BLL.article();
            BLL.category cbll = new BLL.category();
            Model.channel channel = bll.GetModel(name);

            StringBuilder strCategorys = new StringBuilder();
            string[] idArr;
            if (string.IsNullOrEmpty(channel.bind_id))
            {
                idArr = new string[] { channel.id.ToString() };
            }
            else
            {
                idArr = channel.bind_id.Split(',');
            }
            foreach (string item in idArr)
            {
                int bind_id;
                if (int.TryParse(item, out bind_id))
                {
                    Model.channel bind_channel = new BLL.channel().GetModel(bind_id);
                    if (bind_channel.model_id == (int)Enums.sys_model.内容模块)
                    {
                        if (bind_channel.show_category == 0)
                        {
                            DataTable dt = abll.GetList(bind_id).Tables[0];
                            if (dt.Rows.Count > 0)
                            {
                                foreach (DataRow dr in dt.Rows)
                                {
                                    strCategorys.AppendFormat("<a href=\"{0}\">{1}</a>", GetPageUrl(dr["link_url"].ToString(), bind_channel.name, Convert.ToInt32(dr["id"])), dr["title"]);
                                }
                            }
                        }
                        else
                        {
                            DataTable dt = cbll.GetList(string.Format("channel_id={0} and parent_id=0 order by sort_id asc", bind_id)).Tables[0];
                            if (dt.Rows.Count > 0)
                            {
                                foreach (DataRow dr in dt.Rows)
                                {
                                    strCategorys.AppendFormat("<a href=\"javascript:void(0);\">{0}</a>", dr["title"]);
                                }
                            }
                        }
                    }
                    else
                    {

                        DataTable dt = cbll.GetList(string.Format("channel_id={0} and parent_id=0 order by sort_id asc", bind_id)).Tables[0];
                        if (dt.Rows.Count > 0)
                        {
                            foreach (DataRow dr in dt.Rows)
                            {
                                strCategorys.AppendFormat("<a href=\"{0}\">{1}</a>", HtmlHelper.GetListUrl(dr["link_url"].ToString(), bind_channel.name, Convert.ToInt32(dr["id"])), dr["title"]);
                            }
                        }
                    }
                }
            }
            return strCategorys.ToString();
        }

        public static string GetListUrl(string link_url, string name, int category_id)
        {
            if (string.IsNullOrEmpty(link_url.Trim()))
            {
                return url("list", name, category_id);
            }
            else
            {
                return link_url;
            }
        }

        public static string GetPageUrl(string link_url, string name, int id)
        {
            if (string.IsNullOrEmpty(link_url.Trim()))
            {
                return url("page", name, id);
            }
            else
            {
                return link_url;
            }
        }

        public static string GetCategoryList(string name)
        {
            BLL.category bll = new BLL.category();
            StringBuilder strTemp = new StringBuilder();
            DataTable dt = bll.GetListByName(0, name);
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    strTemp.AppendFormat("<li class=\"sub{0}\" cateId=\"{1}\"><a href=\"{2}\" {3}>{4}</a></li>", dr["layer"], dr["id"], HtmlHelper.GetListUrl(dr["link_url"].ToString(), name, Convert.ToInt32(dr["id"])), GetArticleCurrentClass(dr["id"]), dr["title"]);
                }
            }
            return strTemp.ToString();
        }

        public static string GetContentList(string name)
        {
            BLL.article bll = new BLL.article();
            StringBuilder strTemp = new StringBuilder();
            string condition = string.Format("category_id in(select id from he_category where channel_id in(select id from he_channel where name='{0}')) order by sort_id asc,id desc", name);
            DataTable dt = bll.GetList(condition).Tables[0];
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    strTemp.AppendFormat("<li class=\"sub1\" cateId=\"{0}\"><a href=\"{1}\" {2}>{3}</a></li>", dr["id"], GetPageUrl(dr["link_url"].ToString(), name, Convert.ToInt32(dr["id"])), GetContentCurrentClass(name, dr["id"], bll.GetFirstId(name)), dr["title"]);
                }
            }
            return strTemp.ToString();
        }

        public static string GetCateAndArticleList(string name)
        {
            BLL.category bll = new BLL.category();
            BLL.article abll = new BLL.article();
            StringBuilder strTemp = new StringBuilder();
            DataTable dt = bll.GetListByName(0, name);
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    strTemp.AppendFormat("<li class=\"sub{0}\" cateId=\"{1}\"><a href=\"javascript:void(0);\">{2}</a></li>", dr["layer"], dr["id"], dr["title"]);
                    DataTable dt2 = abll.GetList("category_id=" + dr["id"]).Tables[0];
                    if (dt2.Rows.Count > 0)
                    {
                        foreach (DataRow dr2 in dt2.Rows)
                        {
                            strTemp.AppendFormat("<li class=\"sub2\" cateId=\"{0}\"><a href=\"{1}\" {2}>{3}</a></li>", dr2["id"], GetPageUrl(dr["link_url"].ToString(), name, Convert.ToInt32(dr2["id"])), GetContentCurrentClass(name, dr2["id"], abll.GetFirstId(name)), dr2["title"]);
                        }
                    }
                }
            }
            return strTemp.ToString();
        }

        public static string GetArticleCurrentClass(object cateId)
        {
            if (HttpContext.Current.Request["category_id"] == cateId.ToString())
            {
                return " class=\"current\" ";
            }
            return string.Empty;
        }

        public static string GetContentCurrentClass(string name, object id, int default_id)
        {
            if (HttpContext.Current.Request["id"] == null)
            {
                if (InputUtil.Get("name") == name)
                {
                    if (id.ToString() == default_id.ToString())
                    {
                        return " class=\"current\" ";
                    }
                }
            }
            if (HttpContext.Current.Request["id"] == id.ToString())
            {
                return " class=\"current\" ";
            }
            return string.Empty;
        }

        #endregion

        #region 后台分页
        public static string PagerText(int _pcount, int _pagesize, int _page, string _link)
        {
            if (_pcount == 0)
            {
                return "<div style='text-align:center;color:#f00'>当前没有相应的数据！</div>";
            }


            StringBuilder strTxt = new StringBuilder();
            strTxt.Append("<script type=\"text/javascript\" src=\"../../plug/pagination/jquery.pagination.js\"></script>\n");
            strTxt.Append("<script type=\"text/javascript\">\n");
            strTxt.Append("$(function(){\n");
            strTxt.Append("\t$(\"#Pagination\").pagination(" + _pcount + ",{\n");
            strTxt.Append("\t\t callback:pageselectCallback,\n");
            strTxt.Append("\t\t prev_text:\"« 上一页\",\n");
            strTxt.Append("\t\t next_text:\"下一页 »\",\n");
            strTxt.Append("\t\t items_per_page:" + _pagesize + ",\n");
            strTxt.Append("\t\t num_display_entries:3,\n");
            strTxt.Append("\t\t current_page:" + _page + ",\n");
            strTxt.Append("\t\t num_edge_entries:2,\n");
            strTxt.Append("\t\t link_to:\"" + _link + "\"\n");
            strTxt.Append("\t});\n");
            strTxt.Append("});\n");
            strTxt.Append("function pageselectCallback(page_id, jq){\n");
            strTxt.Append("\t //alert(page_id); 回调函数，进一步使用请参阅说明文档\n");
            strTxt.Append("}\n");
            strTxt.Append("</script>\n");
            strTxt.Append("<div id=\"Pagination\" class=\"flickr\" style='background:none'  ></div>\n");
            return strTxt.ToString();
        }
        #endregion

        #region 前台分页
        /// <summary>
        /// 返回分页页码(中文)
        /// </summary>
        /// <param name="pageSize">页面大小</param>
        /// <param name="pageIndex">当前页</param>
        /// <param name="totalCount">总记录数</param>
        /// <param name="linkUrl">链接地址，__id__代表页码</param>
        /// <param name="centSize">中间页码数量</param>
        /// <returns></returns>
        public static string OutPageList(int pageSize, int pageIndex, int totalCount, string linkUrl)
        {
            int centSize = 10;//为偶数
            string noText = "<div style='text-align:center;color:#f00'>当前没有相应的数据！</div>";
            //计算页数
            if (totalCount < 1 || pageSize < 1)
            {
                return noText;
            }
            int pageCount = totalCount / pageSize;
            if (totalCount % pageSize > 0)
            {
                pageCount += 1;
            }
            StringBuilder pageStr = new StringBuilder();
            pageStr.Append("<div class=\"black\">");
            string pageId = "__id__";
            string firstBtn = "<a href=\"" + StringHelper.ReplaceStr(linkUrl, pageId, "0") + "\">首页</a><a href=\"" + StringHelper.ReplaceStr(linkUrl, pageId, (pageIndex - 1).ToString()) + "\">上一页</a>";
            string lastBtn = "<a href=\"" + StringHelper.ReplaceStr(linkUrl, pageId, (pageIndex + 1).ToString()) + "\">下一页</a><a href=\"" + StringHelper.ReplaceStr(linkUrl, pageId, (pageCount - 1).ToString()) + "\">尾页</a>";
            string firstStr = "<a href=\"" + StringHelper.ReplaceStr(linkUrl, pageId, "0") + "\">1</a>";
            string lastStr = "<a href=\"" + StringHelper.ReplaceStr(linkUrl, pageId, (pageCount - 1).ToString()) + "\">" + pageCount.ToString() + "</a>";

            if (pageIndex <= 0)
            {
                firstBtn = "";
            }
            if (pageIndex + 1 >= pageCount)
            {
                lastBtn = "";
            }
            if (pageIndex == 0)
            {
                firstStr = "<span class=\"current\">1</span>";
            }
            if (pageIndex + 1 == pageCount)
            {
                lastStr = "<span class=\"current\">" + pageCount.ToString() + "</span>";
            }
            if (pageCount == 1)
            {
                lastStr = "";
            }
            int firstNum = pageIndex + 1 - (centSize / 2); //中间开始的页码
            if (firstNum < 2)
                firstNum = 2;
            int lastNum = pageIndex + 1 + centSize - ((centSize / 2)); //中间结束的页码
            if (lastNum >= pageCount)
                lastNum = pageCount - 1;
            pageStr.Append(firstBtn);
            if (pageIndex > centSize / 2)
            {
                pageStr.Append("<a href=\"" + StringHelper.ReplaceStr(linkUrl, pageId, (firstNum - 2).ToString()) + "\">...</a>\n");
            }
            else
            {
                pageStr.Append(firstStr);
            }
            for (int i = firstNum; i <= lastNum; i++)
            {
                if (i - 1 == pageIndex)
                {
                    pageStr.Append("<span class=\"current\">" + i + "</span>");
                }
                else
                {
                    pageStr.Append("<a href=\"" + StringHelper.ReplaceStr(linkUrl, pageId, (i - 1).ToString()) + "\">" + i + "</a>");
                }
            }
            if (pageCount - (pageIndex + 1) > centSize - ((centSize / 2)))
            {
                pageStr.Append("<a href=\"" + StringHelper.ReplaceStr(linkUrl, pageId, (lastNum).ToString()) + "\">...</a>");
            }
            else
            {
                pageStr.Append(lastStr);
            }
            pageStr.Append(lastBtn);
            pageStr.Append("</div>");
            return pageStr.ToString();
        }
        /// <summary>
        /// 返回分页页码(英文)
        /// </summary>
        /// <param name="pageSize">页面大小</param>
        /// <param name="pageIndex">当前页</param>
        /// <param name="totalCount">总记录数</param>
        /// <param name="linkUrl">链接地址，__id__代表页码</param>
        /// <param name="centSize">中间页码数量</param>
        /// <returns></returns>
        public static string OutPageListEn(int pageSize, int pageIndex, int totalCount, string linkUrl)
        {
            int centSize = 10;//为偶数
            string noText = "<div style='text-align:center;color:#f00'>No data！</div>";
            //计算页数
            if (totalCount < 1 || pageSize < 1)
            {
                return noText;
            }
            int pageCount = totalCount / pageSize;
            if (totalCount % pageSize > 0)
            {
                pageCount += 1;
            }
            StringBuilder pageStr = new StringBuilder();
            pageStr.Append("<div class=\"black\">");
            string pageId = "__id__";
            string firstBtn = "<a href=\"" + StringHelper.ReplaceStr(linkUrl, pageId, "0") + "\">Home</a><a href=\"" + StringHelper.ReplaceStr(linkUrl, pageId, (pageIndex - 1).ToString()) + "\">Prev</a>";
            string lastBtn = "<a href=\"" + StringHelper.ReplaceStr(linkUrl, pageId, (pageIndex + 1).ToString()) + "\">Next</a><a href=\"" + StringHelper.ReplaceStr(linkUrl, pageId, (pageCount - 1).ToString()) + "\">Last</a>";
            string firstStr = "<a href=\"" + StringHelper.ReplaceStr(linkUrl, pageId, "0") + "\">1</a>";
            string lastStr = "<a href=\"" + StringHelper.ReplaceStr(linkUrl, pageId, (pageCount - 1).ToString()) + "\">" + pageCount.ToString() + "</a>";

            if (pageIndex <= 0)
            {
                firstBtn = "";
            }
            if (pageIndex + 1 >= pageCount)
            {
                lastBtn = "";
            }
            if (pageIndex == 0)
            {
                firstStr = "<span class=\"current\">1</span>";
            }
            if (pageIndex + 1 == pageCount)
            {
                lastStr = "<span class=\"current\">" + pageCount.ToString() + "</span>";
            }
            if (pageCount == 1)
            {
                lastStr = "";
            }
            int firstNum = pageIndex + 1 - (centSize / 2); //中间开始的页码
            if (firstNum < 2)
                firstNum = 2;
            int lastNum = pageIndex + 1 + centSize - ((centSize / 2)); //中间结束的页码
            if (lastNum >= pageCount)
                lastNum = pageCount - 1;
            pageStr.Append(firstBtn);
            if (pageIndex > centSize / 2)
            {
                pageStr.Append("<a href=\"" + StringHelper.ReplaceStr(linkUrl, pageId, (firstNum - 2).ToString()) + "\">...</a>\n");
            }
            else
            {
                pageStr.Append(firstStr);
            }
            for (int i = firstNum; i <= lastNum; i++)
            {
                if (i - 1 == pageIndex)
                {
                    pageStr.Append("<span class=\"current\">" + i + "</span>");
                }
                else
                {
                    pageStr.Append("<a href=\"" + StringHelper.ReplaceStr(linkUrl, pageId, (i - 1).ToString()) + "\">" + i + "</a>");
                }
            }
            if (pageCount - (pageIndex + 1) > centSize - ((centSize / 2)))
            {
                pageStr.Append("<a href=\"" + StringHelper.ReplaceStr(linkUrl, pageId, (lastNum).ToString()) + "\">...</a>");
            }
            else
            {
                pageStr.Append(lastStr);
            }
            pageStr.Append(lastBtn);
            pageStr.Append("</div>");
            return pageStr.ToString();
        }
        #endregion

        #region 获取所有模块
        public string GetAllModels(string lang)
        {
            Model.webset webset = new BLL.webset().GetWebset();
            Model.site_info siteinfo = new BLL.site_info().GetModelByLang(lang);

            StringBuilder strTemp = new StringBuilder();

            strTemp.Append("<div style=\"line-height:30px;\">");

            strTemp.AppendFormat("<span onclick=\"getLink(this)\" link=\"{0}\"><strong><a href=\"#\">首页</a></strong></span><br />", siteinfo.EnginePage);

            DataTable dt = new channel().GetList(string.Format("lang='{0}' and is_lock=0", lang)).Tables[0];
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    int model_id = Convert.ToInt32(dr["model_id"]);
                    if (model_id == (int)Enums.sys_model.内容模块)
                    {
                        strTemp.AppendFormat("<span onclick=\"getLink(this)\" link=\"?p=content&name={0}\"><strong><a href=\"#\">{1}</a></strong></span>:", dr["name"], dr["manage_title"]);
                        DataTable dtt = new BLL.article().GetList(Convert.ToInt32(dr["id"])).Tables[0];
                        if (dtt.Rows.Count > 0)
                        {
                            foreach (DataRow drr in dtt.Rows)
                            {
                                strTemp.AppendFormat("<span onclick=\"getLink(this)\" link=\"?p=content&name={0}&id={1}\"><a href=\"#\">{2}</a></span> ", dr["name"], drr["id"], drr["title"]);
                            }
                        }
                    }
                    else
                    {
                        strTemp.AppendFormat("<span onclick=\"getLink(this)\" link=\"?p=list&name={0}\"><strong><a href=\"#\">{1}</a></strong></span>:", dr["name"], dr["manage_title"]);
                        DataTable dtt = new BLL.category().GetList(0, Convert.ToInt32(dr["id"]));
                        if (dtt.Rows.Count > 0)
                        {
                            foreach (DataRow drr in dtt.Rows)
                            {
                                strTemp.AppendFormat("<span onclick=\"getLink(this)\" link=\"?p=list&name={0}&category_id={1}\"><a href=\"#\">{2}</a></span> ", dr["name"], drr["id"], drr["title"]);
                            }
                        }
                    }
                    strTemp.Append("<br />");
                }
                //仅显示分类
                foreach (DataRow dr in dt.Rows)
                {
                    strTemp.AppendFormat("<span onclick=\"getLink(this)\" link=\"?p=category&name={0}\"><strong><a href=\"#\">{1}(仅分类)</a></strong></span><br /> ", dr["name"], dr["title"]);
                }
            }

            List<Model.plug> pluglst = new He.BLL.config().LoadConfig<List<Model.plug>>("~/config/plug.config");
            foreach (Model.plug cl in pluglst)
            {
                if (cl.Lang == lang)
                {
                    strTemp.AppendFormat("<span link=\"?p={0}\" onclick=\"getLink(this)\"><strong><a href=\"#\">{1}</a></strong></span><br />", cl.Value, cl.Name);
                }
            }

            strTemp.Append("</div>");

            return strTemp.ToString();
        }
        #endregion

        #region 转换为HTML换行标签
        public static string ReplaceToNewLine(string src)
        {
            return src.Replace("\n", "<br />");
        }
        #endregion

        #region 列表页跳转地址
        public static string GetShowUrl(int id, string link_url)
        {
            if (string.IsNullOrEmpty(link_url))
            {
                return url("show", id);
            }
            else
            {
                return link_url;
            }
        }
        #endregion

        #region 详情页展示效果

        /// <summary>
        /// 替换myfocus效果中的效果字符
        /// </summary>
        /// <param name="effect"></param>
        /// <returns></returns>
        public static string ReplaceMyFocusEffect(string effect)
        {
            return Regex.Replace(effect, @"_mF_.*", "", RegexOptions.IgnoreCase);
        }
        #endregion

        #region CSS样式
        public static string currentClass(object currentKey, object destKey, string className = "current")
        {
            if (currentKey != null && destKey != null && currentKey.ToString() == destKey.ToString())
            {
                return className;
            }
            return string.Empty;
        }
        #endregion

        #region 轮播
        /// <summary>
        /// 焦点图轮播
        /// </summary>
        /// <param name="call_mark"></param>
        /// <returns></returns>
        public string ad(string call_mark)
        {
            string cacheKey = "ad_position_" + call_mark;
            string html = CacheHelper.Get(cacheKey) as string;
            if (html == null)
            {
                html = new AdHelper().GetFocusHtml(call_mark);
                CacheHelper.Add(cacheKey, html, 360000);
            }
            return html;
        }

        /// <summary>
        /// 轮播指定栏目下的图片
        /// </summary>
        /// <param name="name"></param>
        /// <param name="top"></param>
        /// <param name="condition"></param>
        /// <param name="w"></param>
        /// <param name="h"></param>
        /// <returns></returns>
        public string focus(string name, int top, string condition, string w, string h)
        {
            StringBuilder sb = new StringBuilder();
            BLL.article bll = new BLL.article();
            List<Model.article> lst = bll.DataTableToList(bll.GetList(name, top, condition, "sort_id asc,id desc").Tables[0]);
            foreach (Model.article pic in lst)
            {
                sb.Append(pic.img_url);
                sb.Append("|");
            }
            return new AdHelper().DefaultFocusHtml(w, h, sb.ToString().Trim('|'), "|||");
        }
        #endregion

        #region 栏目相关
        /// <summary>
        /// 摘要
        /// </summary>
        /// <param name="name"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public string zhaiyao(string name, int length)
        {
            string zhaiyao = new BLL.article().GetModel(name).seo_desc;
            return StringHelper.CutString(zhaiyao, length);
        }

        #endregion

        #region URL重写

        public static string url(string _page, params object[] _values)
        {
            int url_mode = PageBase.webset.url_mode;
            StringBuilder urlParams = new StringBuilder();
            string fileExt = ".aspx";


            switch (url_mode)
            {
                case (int)Enums.UrlMode.原始链接:
                    urlParams.Append("index.aspx?p=" + _page);
                    string[] keyArr;
                    switch (_page)
                    {
                        case "page":
                            keyArr = new string[] { "name", "id" };
                            break;
                        case "list":
                            keyArr = new string[] { "name", "category_id", "page" };
                            break;
                        case "show":
                            keyArr = new string[] { "id" };
                            break;
                        case "plug":
                            keyArr = new string[] { "act" };
                            break;
                        default:
                            keyArr = new string[] { };
                            break;
                    }
                    if (keyArr.Length > 0)
                    {
                        for (int i = 0; i < _values.Length; i++)
                        {
                            if (keyArr[i] != null && _values[i] != null)
                            {
                                urlParams.AppendFormat("&{0}={1}", keyArr[i], _values[i]);
                            }
                        }
                    }
                    break;
                case (int)Enums.UrlMode.html纯静态:
                    fileExt = ".html";
                    break;
                case (int)Enums.UrlMode.aspx伪静态:
                    urlParams.Append(_page);
                    for (int i = 0; i < _values.Length; i++)
                    {
                        if (!string.IsNullOrEmpty(_values[i].ToString()))
                        {
                            urlParams.Append("_" + _values[i]);
                        }
                    }
                    urlParams.Append(fileExt);
                    break;
                case (int)Enums.UrlMode.html伪静态:
                    fileExt = ".html";
                    goto case (int)Enums.UrlMode.aspx伪静态;
            }
            return urlParams.ToString();
        }
        #endregion
    }
}